Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix : View Retention in Users Tab After Navigation and Logout #9485

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from

Conversation

Mahendar0701
Copy link
Contributor

@Mahendar0701 Mahendar0701 commented Dec 18, 2024

Proposed Changes

Recording.2024-12-18.173555.mp4

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Enhanced user management with improved tab view functionality.
    • Dynamic default view settings for resource and shifting routes.
  • Bug Fixes

    • Loading states for user and district data now consistently display a spinner during data fetching.
  • Chores

    • Refactored local storage handling for default views using utility functions for better abstraction.

@Mahendar0701 Mahendar0701 requested a review from a team as a code owner December 18, 2024 12:10
Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Walkthrough

This pull request introduces a new utility module viewStorageUtils.ts with functions getDefaultView and setDefaultView to manage view preferences across different components. The changes standardize how default views are stored and retrieved in local storage for Users, Resources, and Shifting components. The implementation allows components to persistently remember user view preferences (list or card/board) across navigation and logout, addressing the issue of view state not being retained.

Changes

File Change Summary
src/Utils/viewStorageUtils.ts Added two utility functions: getDefaultView and setDefaultView for managing local storage view preferences
src/components/Users/ManageUsers.tsx Updated to use getDefaultView for initializing active tab and setDefaultView for storing view preference
src/Routers/routes/ResourceRoutes.tsx, ShiftingRoutes.tsx Replaced inline getDefaultView with imported utility function
src/components/Resource/ResourceBoard.tsx, ResourceList.tsx Replaced localStorage.setItem with setDefaultView
src/components/Shifting/ShiftingBoard.tsx, ShiftingList.tsx Replaced localStorage.setItem with setDefaultView

Assessment against linked issues

Objective Addressed Explanation
Retain selected view after navigation
Preserve view preference after logout
Consistent view management across components

Possibly related PRs

Suggested labels

needs review, tested, P1

Suggested reviewers

  • rithviknishad
  • Jacobjeevan
  • nihal467

Poem

🐰 A Rabbit's View of Persistence

In local storage, views now dance,
No more forgetting at a glance!
Card or list, the choice is clear,
Remembered now, without a fear.
Hop along, sweet view delight! 🌈


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

netlify bot commented Dec 18, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit db15f8b
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6763132ea9c3cb0008014d8c
😎 Deploy Preview https://deploy-preview-9485--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/Routers/routes/UserRoutes.tsx (1)

14-16: Consider adding type safety for view parameter.

While the implementation is clean, consider adding runtime validation for the view parameter to prevent potential routing issues with invalid values.

-  "/users": () => <Redirect to={`/users/${getDefaultUsersView()}`} />,
+  "/users": () => {
+    const view = getDefaultUsersView();
+    if (view !== "list" && view !== "card") {
+      console.error(`Invalid view type: ${view}`);
+      return <Redirect to="/users/card" />;
+    }
+    return <Redirect to={`/users/${view}`} />;
+  },
src/components/Users/ManageUsers.tsx (1)

108-113: Consider adding error handling for navigation failures.

The handleTabChange function looks good but should handle potential navigation failures.

   const handleTabChange = (tab: number) => {
     setActiveTab(tab);
     const newView = tab === 1 ? "list" : "card";
     localStorage.setItem("usersDefaultView", newView);
-    navigate(`/users/${newView}`);
+    navigate(`/users/${newView}`).catch((error) => {
+      console.error("Navigation failed:", error);
+      // Optionally show a user-friendly error notification
+    });
   };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3979b53 and 51a053e.

📒 Files selected for processing (2)
  • src/Routers/routes/UserRoutes.tsx (1 hunks)
  • src/components/Users/ManageUsers.tsx (4 hunks)
🔇 Additional comments (3)
src/Routers/routes/UserRoutes.tsx (1)

10-11: LGTM! Clean implementation of view preference retrieval.

The function is well-focused and provides a good fallback mechanism.

src/components/Users/ManageUsers.tsx (2)

31-31: LGTM! Well-structured component initialization.

The component properly handles the defaultView prop and initializes the state accordingly.

Also applies to: 50-50


121-123: Verify the integration with UserListView component.

Ensure that the UserListView component properly handles the tab change callback.

✅ Verification successful

The UserListView component properly handles the tab change callback

The verification shows that:

  • The UserListView component in UserListAndCard.tsx correctly defines the onTabChange prop in its interface as onTabChange: (tab: number) => void
  • The component properly receives and uses the onTabChange prop to handle tab changes
  • The implementation in ManageUsers.tsx correctly passes the handleTabChange callback to the UserListView component
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for UserListView component implementation to verify onTabChange prop handling
ast-grep --pattern 'interface $interface {
  $$$
  onTabChange: $type
  $$$
}'

# Search for actual usage of onTabChange in the component
ast-grep --pattern 'function UserListView($props) {
  $$$
  onTabChange($$$)
  $$$
}'

Length of output: 168


Script:

#!/bin/bash
# Let's try a broader search for UserListView component and its props
rg -A 10 "UserListView" --type typescript

# Also search for any file containing UserListView in its name
fd UserListView

# Search for tab change handling patterns
rg "onTabChange|handleTabChange" --type typescript

Length of output: 182


Script:

#!/bin/bash
# Search for UserListView component and its props without type filter
rg -A 10 "UserListView"

# Search for any file containing UserListView in its name
fd UserListView

# Search for tab change handling patterns
rg "onTabChange|handleTabChange"

Length of output: 6358

src/components/Users/ManageUsers.tsx Outdated Show resolved Hide resolved
@rithviknishad
Copy link
Member

I'd recommend creating a util. function that handles the logic to create an abstraction between the storage, since we have similar use cases in other places.

@rithviknishad
Copy link
Member

Also, let's not have a dedicated route defined for it.

@Jacobjeevan
Copy link
Contributor

I'd recommend creating a util. function that handles the logic to create an abstraction between the storage, since we have similar use cases in other places.

Oh true, resources and shifting if I recall.

@rithviknishad
Copy link
Member

rithviknishad commented Dec 18, 2024

And appointments page in DO Branch, (although the list view is not ready there yet)

@Mahendar0701
Copy link
Contributor Author

Also, let's not have a dedicated route defined for it.

For Users i have done.

Comment on lines 13 to 19
"/shifting": () => (
<Redirect
to={`/shifting/${getDefaultView("defaultResourceView", "board")}`}
/>
),
"/shifting/board": () => <BoardView />,
"/shifting/list": () => <ListView />,
Copy link
Contributor Author

@Mahendar0701 Mahendar0701 Dec 18, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Jacobjeevan @rithviknishad Shifting and Resources tabs have two dedicated components for each list and board view and dedicated routes for them.

Should i call them in a single file and conditionally handle the views or let it be same

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/Routers/routes/ShiftingRoutes.tsx (1)

Line range hint 1-1: Consider centralizing localStorage keys

To improve maintainability and prevent key conflicts, consider creating a central constants file for localStorage keys:

// src/constants/storage.ts
export const STORAGE_KEYS = {
  VIEWS: {
    USERS: 'usersDefaultView',
    RESOURCES: 'resourcesDefaultView',
    SHIFTING: 'shiftingDefaultView'
  }
} as const;

This would provide:

  1. Type safety for keys
  2. Easy discovery of existing keys
  3. Prevention of duplicate keys
  4. Single source of truth for storage keys
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 51a053e and 8af90dd.

📒 Files selected for processing (5)
  • src/Routers/routes/ResourceRoutes.tsx (1 hunks)
  • src/Routers/routes/ShiftingRoutes.tsx (1 hunks)
  • src/Routers/routes/UserRoutes.tsx (1 hunks)
  • src/Utils/viewStorageUtils.ts (1 hunks)
  • src/components/Users/ManageUsers.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/Routers/routes/UserRoutes.tsx
  • src/components/Users/ManageUsers.tsx

src/Utils/viewStorageUtils.ts Show resolved Hide resolved
src/Utils/viewStorageUtils.ts Show resolved Hide resolved
src/Routers/routes/ResourceRoutes.tsx Show resolved Hide resolved
src/Routers/routes/ShiftingRoutes.tsx Outdated Show resolved Hide resolved
Comment on lines +1 to +7
export const getDefaultView = (key: string, defaultValue: string): string => {
return localStorage.getItem(key) || defaultValue;
};

export const setDefaultView = (key: string, value: string): void => {
localStorage.setItem(key, value);
};
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant something like:

const [view, setView] = useView("shifting");

Comment on lines 13 to 19
"/shifting": () => (
<Redirect
to={`/shifting/${getDefaultView("defaultShiftingView", "board")}`}
/>
),
"/shifting/board": () => <BoardView />,
"/shifting/list": () => <ListView />,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yup, let's remove these routes too and instead we could do:

(which uses that hook behind the scenes)

"/shifting": () => <View 
  name="shifting"
  board={BoardView}
  list={ListView}
  />

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
src/components/Shifting/ShiftingList.tsx (2)

39-39: Consider calling setDefaultView before navigation

For better user experience, consider storing the view preference before navigating to prevent any potential race conditions.

const onBoardViewBtnClick = () => {
+  setDefaultView("defaultShiftView", "board");
  navigate("/shifting/board", { query: qParams });
-  setDefaultView("defaultShiftView", "board");
};

22-22: Consider using constants for view types and storage keys

To maintain consistency and prevent typos, consider extracting the view types and storage keys into constants.

// Add to a constants file
export const VIEW_TYPES = {
  BOARD: 'board',
  LIST: 'list'
} as const;

export const STORAGE_KEYS = {
  SHIFT_VIEW: 'defaultShiftView',
  RESOURCE_VIEW: 'defaultResourceView',
  USER_VIEW: 'defaultUserView'
} as const;

Also applies to: 39-39

src/components/Resource/ResourceBoard.tsx (1)

51-51: Apply consistent view management pattern

Similar to the ShiftingList component, consider:

  1. Moving setDefaultView before navigation
  2. Using constants for view types and storage keys
const onListViewBtnClick = () => {
+  setDefaultView(STORAGE_KEYS.RESOURCE_VIEW, VIEW_TYPES.LIST);
  navigate("/resource/list", { query: qParams });
-  setDefaultView("defaultResourceView", "list");
};
src/components/Shifting/ShiftingBoard.tsx (2)

82-82: Apply consistent view management pattern

Similar to other components, consider:

  1. Moving setDefaultView before navigation
  2. Using constants for view types and storage keys
const onListViewBtnClick = () => {
+  setDefaultView(STORAGE_KEYS.SHIFT_VIEW, VIEW_TYPES.LIST);
  navigate("/shifting/list", { query: qParams });
-  setDefaultView("defaultShiftView", "list");
};

33-33: Consider creating a reusable view switching hook

There's a pattern of duplicated view switching logic across components. Consider creating a custom hook to encapsulate this behavior.

// src/hooks/useViewSwitcher.ts
import { navigate } from "raviger";
import { setDefaultView } from "@/Utils/viewStorageUtils";
import { VIEW_TYPES, STORAGE_KEYS } from "@/common/constants";

type ViewConfig = {
  storageKey: typeof STORAGE_KEYS[keyof typeof STORAGE_KEYS];
  listPath: string;
  boardPath: string;
};

export const useViewSwitcher = (config: ViewConfig) => {
  const switchToListView = (qParams: Record<string, any>) => {
    setDefaultView(config.storageKey, VIEW_TYPES.LIST);
    navigate(config.listPath, { query: qParams });
  };

  const switchToBoardView = (qParams: Record<string, any>) => {
    setDefaultView(config.storageKey, VIEW_TYPES.BOARD);
    navigate(config.boardPath, { query: qParams });
  };

  return { switchToListView, switchToBoardView };
};

// Usage in components:
const { switchToListView } = useViewSwitcher({
  storageKey: STORAGE_KEYS.SHIFT_VIEW,
  listPath: "/shifting/list",
  boardPath: "/shifting/board"
});

// Replace onListViewBtnClick with:
const onListViewBtnClick = () => switchToListView(qParams);

This approach would:

  1. Reduce code duplication
  2. Ensure consistent implementation across components
  3. Make it easier to modify view switching behavior globally
  4. Improve maintainability

Also applies to: 82-82

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8af90dd and db15f8b.

📒 Files selected for processing (6)
  • src/Routers/routes/ShiftingRoutes.tsx (1 hunks)
  • src/components/Resource/ResourceBoard.tsx (2 hunks)
  • src/components/Resource/ResourceList.tsx (2 hunks)
  • src/components/Shifting/ShiftingBoard.tsx (2 hunks)
  • src/components/Shifting/ShiftingList.tsx (2 hunks)
  • src/components/Users/ManageUsers.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/Routers/routes/ShiftingRoutes.tsx
🔇 Additional comments (3)
src/components/Resource/ResourceList.tsx (1)

25-25: LGTM: View persistence implementation looks good!

The implementation correctly uses the setDefaultView utility to persist the view preference when switching to board view.

Also applies to: 41-41

src/components/Users/ManageUsers.tsx (2)

51-53: LGTM: Proper initialization of view preference!

The implementation correctly retrieves the stored view preference with a sensible default of "card" view.


111-115: LGTM: Clean implementation of view persistence!

The handleTabChange function properly manages both the local state and persistent storage of the view preference. The implementation is concise and follows the single responsibility principle.

Also applies to: 124-124

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Selected View in Users Tab Not Retained After Navigation or Logout
3 participants